
import styles from './style.less';
import { connect, Link, history } from 'umi';
import DirMenu from '@/components/doc/DirMenu'
import { DOC_TYPE } from '@/consts/doc';
import { useEffect, useState, useRef } from 'react';
import { SearchOutlined, FileAddOutlined, QuestionCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { Form, Input, Modal, Select, Table, Space, Button, Popover } from 'antd';
import { listDataModel, saveDataModel, updateDataModel } from '@/services/doc/api'
import TextButton from '@/components/TextButton'
import ApiParamEditTable from '../ApiParamEditTable'

const { Option } = Select;

const ApiDataModel = (props) => {
    const {
        projectId,
        projectPermission,
        routeParam,
    } = props;

    const [currentDocData, setCurrentDocData] = useState();
    const [dataModalList, setDataModalList] = useState([]);
    const [showedDataModalList, setShowedDataModalList] = useState([]);
    const [searchValue, setSearchValue] = useState({});
    const [currentDir, setCurrentDir] = useState();
    const [tableLoading, setTableLoading] = useState();
    const [permisson, setPermission] = useState();
    const [savingLoading, setSavingLoading] = useState(false)
    const [dirList, setDirList] = useState([{
        id: "0",
        title: "/"
    }])
    const [form] = Form.useForm()
    const menu = useRef();

    useEffect(() => {
        if (projectPermission) {
            setPermission(projectPermission?.api)
        }
    }, [projectPermission])

    useEffect(() => {
        if (currentDocData) {
            form.resetFields()
        }
    }, [currentDocData])

    useEffect(() => {
        if (currentDocData) {
            form.resetFields()
        }
    }, [currentDocData])

    useEffect(() => {
        if (projectId) {
            init();
        }
    }, [projectId])

    const init = () => {
        setSearchValue({})
        setCurrentDir()
        setTableLoading(true)
        listDataModel(projectId, {}).then((result) => {
            setDataModalList(result.data)
            setTableLoading(false)
        })
    }

    useEffect(() => {
        if (searchValue) {
            setShowedDataModalList(dataModalList.filter(item => {
                let dirCond = searchValue.dirId ? item.dirId === searchValue.dirId : true;
                let searchTextCond = searchValue.search ? (item.name?.indexOf(searchValue.search) > -1 || item.description?.indexOf(searchValue.search) > -1) : true
                return dirCond && (searchTextCond);
            }))
        } else {
            setShowedDataModalList([...dataModalList])
        }
    }, [searchValue, dataModalList])

    const onDirTreeData = (dirTreeData) => {
        if (dirTreeData) {
            let dirList = [{
                id: "0",
                title: "/"
            }]
            dirTreeData.forEach(dir => {
                if (dir.isDir) {
                    dirList.push({
                        id: dir.id,
                        title: dir.title
                    })
                }
            })
            setDirList(dirList)
        }
    }

    const deleteDocDir = (docDir, callBack) => {
        // 删除接口文档目录
    }


    const addErrorCode = (dir, dirRoutes) => {
        setCurrentDocData({
            dirId: dir.id,
            type: "json",
            content: []
        })
    }

    const onUpdateErrorCode = (dataModal) => {
        setCurrentDocData({
            ...dataModal,
        })
    }

    const onSaveErrorCode = async (doc) => {
        let values = await form.validateFields()
        // console.log(values, content)
        setSavingLoading(true)
        let data = {
            ...values,
            content: currentDocData.newContent.fields
        }
        if (currentDocData.id) {
            updateDataModel(projectId, currentDocData.id, data).then(result => {
                setCurrentDocData(null)
                let newDataModalList = dataModalList.map((item) => {
                    if (item.id === currentDocData.id) {
                        return {
                            ...item,
                            ...data
                        }
                    }
                    return item
                })
                setDataModalList(newDataModalList)
                setSavingLoading(false)
            })
        } else {
            saveDataModel(projectId, data).then(result => {
                setCurrentDocData(null)
                dataModalList.push({
                    id: result.data,
                    ...data
                })
                setDataModalList([...dataModalList])
                setSavingLoading(false)
            })
        }
    }

    const onClickDir = (docNode, dirRoutes) => {
        setCurrentDir(docNode)
        setSearchValue({
            ...searchValue,
            dirId: docNode.id,
        })
    }

    const columns = [{
        title: "名称",
        dataIndex: 'name',
        width: "25%",
        sorter: (a, b) => a.name && a.name.localeCompare(b.name),
    }, {
        title: "类型",
        dataIndex: 'type',
        width: "10%",
    }, {
        title: "描述",
        dataIndex: 'description',
        sorter: (a, b) => a.description && a.description.localeCompare(b.description),
    }]

    const renderTableColumn = () => {
        if (permisson?.errcode) {
            columns.push({
                title: "操作",
                dataIndex: 'action',
                render: (text, record) => <Space>
                    <TextButton onClick={() => onUpdateErrorCode(record)}>修改</TextButton>
                    <TextButton type="danger">删除</TextButton>
                </Space>
            })
        }
        return columns;
    }

    const onValuesChange = (values) => {
        // console.log("dataModal onValuesChange", values)
    }

    const onContentChange = (content) => {
        currentDocData.newContent = content
    }


    return <div className={styles.dataModalBody}>
        <DirMenu
            ref={menu}
            title={<TextButton onClick={init}>所有数据结构</TextButton>}
            projectId={projectId}
            enableLevel={1}
            width="200px"
            docType={DOC_TYPE.API_DATA_MODAL}
            deleteDir={deleteDocDir}
            onClickDir={onClickDir}
            onDirTreeData={onDirTreeData}
            switcherIcon={null}
            dirMoreActions={["rename", "delete"]}
            rootMore={<div></div>}
            dirOpertion={[
                {
                    key: "addErrorCode",
                    icon: <FileAddOutlined />,
                    name: "新建数据结构",
                    onClick: addErrorCode
                }
            ]}
        >
        </DirMenu>
        <div className={styles.dataModal} style={{
            width: "calc(100% - 200px)"
        }}>

            <div className={styles.dataModalInfo}>
                <Space className={styles.opertion}>
                    <div className={styles.route}>
                        {currentDir ? currentDir.title : "全部"}
                    </div>
                    <Button type="primary" onClick={() => {
                        addErrorCode(currentDir || {
                            id: "0",
                            type: "1"
                        })
                    }}>新增</Button>
                    <Popover content={<p>
                        数据模型:<br />
                        1.建议数据类型为基本数据类型（string、number、file） 。<br />
                        2.object、array类型不支持添加子参数 。<br />
                    </p>}><QuestionCircleOutlined /></Popover>
                </Space>
                <div className={styles.searchInput}>
                    <Input bordered={false}
                        allowClear
                        value={searchValue?.search}
                        onChange={(e) => {
                            setSearchValue({
                                ...searchValue,
                                search: e.target.value
                            })
                        }}
                        prefix={<SearchOutlined />} placeholder={"名称/描述"}></Input>
                </div>

            </div>
            <div className={styles.dataModalList}>
                <Table
                    size="small"
                    rowKey="id"
                    loading={tableLoading}
                    scroll={{ y: 480 }}
                    bordered={false}
                    pagination={false}
                    columns={renderTableColumn()}
                    dataSource={showedDataModalList}
                    expandable={{
                        expandedRowRender: record =><div className={styles.paramTableView}><ApiParamEditTable mode="view" value={{ fields: record?.content }} /></div>,
                        rowExpandable: record => !!record.content,
                        expandedRowClassName:() => styles.expandedRowClassName
                    }}
                >

                </Table>
            </div>

        </div>

        <Modal
            title={currentDocData?.id ? "修改数据接口" : "新增数据结构"}
            visible={!!currentDocData}
            closable
            width="80%"
            zIndex={1051}
            onCancel={() => {
                setCurrentDocData(null)
            }}
            confirmLoading={savingLoading}
            onOk={onSaveErrorCode}
        >
            <Form form={form} className={styles.form} onValuesChange={onValuesChange} initialValues={currentDocData}>
                <Form.Item name="dirId" label="目录">
                    <Select placeholder="请选择目录" dropdownStyle={{ zIndex: 1060 }}>
                        {dirList.map(dir => <Option key={dir.id} value={dir.id}>{dir.title}</Option>)}
                    </Select>
                </Form.Item>
                <Form.Item name="name" label="名字" rules={[{
                    required: true,
                    message: "名称长度为1～40",
                    min: 1,
                    max: 40
                }]}>
                    <Input disabled={!!currentDocData?.id} placeholder="请输入名字"></Input>
                </Form.Item>
                <Form.Item name="type" label="类型" >
                    <Select placeholder="请选择类型" dropdownStyle={{ zIndex: 1060 }}>
                        <Option key="json" value="json">json</Option>
                    </Select>
                </Form.Item>
                <Form.Item name="description" label="描述" rules={[{
                    required: true,
                    message: "描述长度为1～40",
                    min: 1,
                    max: 40
                }]}>
                    <Input placeholder="请选择描述"></Input>
                </Form.Item>
                <Form.Item label="内容">
                    <ApiParamEditTable hasChildren={false} onChange={onContentChange} value={{ fields: currentDocData?.content }} className={styles.contentTable} actions={["import"]}></ApiParamEditTable>
                </Form.Item>
            </Form>
        </Modal>
    </div>
}

export default ApiDataModel;